import Food from "./Food";
import Score from "./Score";
import Snake from "./Snake";

class GameControl {

    snake: Snake;

    food:Food

    direction: number = 40;//默认的方向是向下的

    alive:boolean = true;// 游戏是否还在运行中

    score:Score

    constructor(){
        this.food = new Food();
        this.score = new Score();
        this.snake = new Snake();
        this.init()
    }

    init() {
        document.addEventListener("keydown",this.keydownHandler.bind(this))
        // 让游戏运行起来
        this.run()
    }
    /**
     * 让游戏运行起来
     */
    run(){
        try {
            this.snake.moveDirection(this.direction,this.food,this.score)
        } catch (error) {
            alert((<Error>error).message)
            this.alive = false;
        }
        this.alive && setTimeout(this.run.bind(this), 400 / this.score.level);

    }

    /**
     * 键盘按键按下事件处理函数
     * @param e 键盘事件对象
     */
    keydownHandler(e: KeyboardEvent) {
        // 如果按键码小于37或大于40，则返回
        if (e.keyCode < 37 || e.keyCode > 40){
            return;
        }
        // 根据当前方向切换按键码
        switch (this.direction) {
            case 37: //向右
                this.direction = e.keyCode == 39 ? this.direction : e.keyCode;
                break;
            case 38: //向上
                this.direction = e.keyCode == 40 ? this.direction : e.keyCode;
                break;
            case 39://向左
                this.direction = e.keyCode == 37 ? this.direction : e.keyCode;
                break;
            case 40: //向下
                this.direction = e.keyCode == 38 ? this.direction : e.keyCode;
                break;
        }
    }
}

export default GameControl